<template>
    <view class="rank-page">
        <v-statusbar class="status-bar"></v-statusbar>
        <!-- 顶部导航栏 -->
        <view class="header">
            <view class="header-left" @tap="goBack">
                <uni-icons type="left" size="24" color="#333"></uni-icons>
            </view>
            <view class="page-title">学习排行榜</view>
            <view class="header-right"></view>
        </view>

        <!-- 排行榜内容 -->
        <view class="rank-content">
            <!-- 标签切换 - 滑动门样式 -->
            <view class="rank-tabs">
                <view class="tab-wrapper">
                    <view class="tab-item" :class="{ active: currentTab === 0 }" @tap="switchTab(0)">
                        周榜
                    </view>
                    <view class="tab-item" :class="{ active: currentTab === 1 }" @tap="switchTab(1)">
                        月榜
                    </view>
                    <view class="tab-item" :class="{ active: currentTab === 2 }" @tap="switchTab(2)">
                        年榜
                    </view>
                    <view class="slider" :style="{ transform: `translateX(${sliderPosition}%)` }"></view>
                </view>
            </view>

            <!-- 排行榜数据容器 -->
            <view class="rank-data-container">
                <!-- 刷新提示 -->
                <view class="refresh-tip">
                    <span class="tip-text">- - - 此榜单两小时刷新 - - -</span>
                </view>

                <!-- 前三名  -->
                <view class="top-three">
                    <view class="rank-item third-place" v-if="rankList.length >= 3">
                        <image class="crown" src="/static/image/rank/crown.png" mode="aspectFill"></image>
                        <image class="avatar" :src="cleanAvatarUrl(rankList[2].avatar)" mode="aspectFill"></image>
                        <text class="name">{{ rankList[2].nickName }}</text>
                        <text class="study-time">{{ rankList[2].studyTime }}</text>

                    </view>
                    <view class="rank-item first-place" v-if="rankList.length >= 1">
                        <image class="crown" src="/static/image/rank/crown.png" mode="aspectFill"></image>
                        <image class="avatar" :src="cleanAvatarUrl(rankList[0].avatar)" mode="aspectFill"></image>
                        <text class="name">{{ rankList[0].nickName }}</text>
                        <text class="study-time">{{ rankList[0].studyTime }}</text>
                    </view>
                    <view class="rank-item second-place" v-if="rankList.length >= 2">
                        <image class="crown" src="/static/image/rank/crown.png" mode="aspectFill"></image>
                        <image class="avatar" :src="cleanAvatarUrl(rankList[1].avatar)" mode="aspectFill"></image>
                        <text class="name">{{ rankList[1].nickName }}</text>
                        <text class="study-time">{{ rankList[1].studyTime }}</text>
                    </view>
                </view>

                <!-- 排行榜列表 - 现代设计 -->
                <view class="rank-list">
                    <view class="rank-item normal-item" v-for="(item, index) in rankList.slice(3, 10)" :key="index">
                        <text class="rank-num">{{ index + 4 }}</text>
                        <image class="user-avatar" :src="cleanAvatarUrl(item.avatar)" mode="aspectFill"></image>
                        <text class="user-name">{{ item.nickName }}</text>
                        <text class="user-study-time">{{ item.studyTime }}</text>
                    </view>
                </view>
            </view>

            <view class="loading" v-if="!rankList.length">
                加载中...
            </view>

            <!-- 个人排名卡片 - 新增部分 -->
            <view class="personal-rank-card" v-if="personalRank && rankList.length">
                <view class="card-title">我的排名</view>
                <view class="personal-item" :class="{ 'current-user': true }">
                    <text class="rank-num">{{ personalRank.rank }}</text>
                    <image class="user-avatar" :src="cleanAvatarUrl(personalRank.avatar)" mode="aspectFill"></image>
                    <text class="user-name">{{ personalRank.nickName }}</text>
                    <text class="user-study-time">{{ personalRank.studyTime }}</text>
                </view>
                <view class="rank-tip" v-if="personalRank.rank > 10">
                    您当前排名 {{ personalRank.rank }}，继续努力冲进前十！
                </view>
            </view>
        </view>
    </view>
</template>

<script>
import { axios } from '@/tools/request'
import mixins from '@/mixins'

export default {
    mixins: [mixins],
    data() {
        return {
            currentTab: 0,
            sliderPosition: 0,
            rankList: [],
            personalRank: null, // 存储个人排名信息
            userId: null // 假设有用户ID
        }
    },
    mounted() {
        // 初始化时获取排行榜数据
        this.getRankData()
        // 获取当前用户ID（这里需要根据实际情况获取）
        this.getCurrentUserId()
    },
    methods: {
        // 返回上一页
        goBack() {
            console.log('goBack');
            this.toPage(-1);
        },

        // 切换标签页
        switchTab(index) {
            // 更新当前标签
            this.currentTab = index

            // 更新滑动门指示器位置
            this.sliderPosition = index * 100

            // 清空当前数据，显示加载状态
            this.rankList = []
            this.personalRank = null

            // 重新获取对应榜单的数据
            this.getRankData()
        },

        // 清理头像URL（处理可能的不完整URL和额外空格）
        cleanAvatarUrl(url) {
            if (!url) {
                return 'https://img.icons8.com/bubbles/100/000000/user.png'
            }

            // 去除首尾空格
            const cleanUrl = url.trim()

            // 检查是否是完整URL
            if (!cleanUrl.startsWith('http')) {
                return `https://${cleanUrl}`
            }
            return cleanUrl
        },

        // 获取当前用户ID（示例方法，需要根据实际情况实现）
        getCurrentUserId() {
            // 这里可以从本地存储、Vuex或全局状态中获取用户ID
            // 示例代码：
            try {
                const userInfo = uni.getStorageSync('userInfo')
                if (userInfo && userInfo.id) {
                    this.userId = userInfo.id
                }
            } catch (e) {
                console.error('获取用户信息失败:', e)
            }
        },

        // 获取排行榜数据
        async getRankData() {
            try {
                // 根据当前选中的榜单类型，获取对应的数据
                const rankType = ['week', 'month', 'year'][this.currentTab]

                // 调用真实API
                const response = await axios.get(`/study/course/studyCourseLog/rank/${rankType}`)
                console.log(response);

                // 更新：新的接口返回的数据结构包含code, success, data, msg字段
                if (response) {
                    this.rankList = response
                    // 处理个人排名数据
                    this.processPersonalRank()
                }
            } catch (error) {
                console.error('获取排行榜数据失败:', error)
                // 可以添加错误提示
                uni.showToast({
                    title: '获取排行榜数据失败',
                    icon: 'none'
                })
            }
        },

        // 处理个人排名数据
        processPersonalRank() {
            if (!this.rankList.length) return

            // 更新：使用me字段查找当前用户，不再需要userId
            const currentUserIndex = this.rankList.findIndex(item => item.me)

            if (currentUserIndex !== -1) {
                // 用户在榜单中
                this.personalRank = {
                    ...this.rankList[currentUserIndex],
                    rank: currentUserIndex + 1
                }
            } else {
                // 用户不在榜单中，设置默认个人排名信息
                this.personalRank = {
                    rank: '未上榜',
                    nickName: '当前用户',
                    studyTime: '0秒',
                    avatar: ''
                }
            }
        },

        // 获取个人排名方法不再需要，可以删除或注释掉
        // async getPersonalRank() {
        //     try {
        //         const rankType = ['week', 'month', 'year'][this.currentTab]
        //         // 假设有获取个人排名的API
        //         const response = await axios.get(`/study/course/studyCourseLog/personalRank/${rankType}`)
        //         
        //         if (response) {
        //             this.personalRank = response
        //         }
        //     } catch (error) {
        //         console.error('获取个人排名失败:', error)
        //         // 可以设置一个默认的个人排名信息
        //         this.personalRank = {
        //             rank: '100+',
        //             nickName: '当前用户',
        //             studyTime: '0分钟',
        //             avatar: ''
        //         }
        //     }
        // }
    }
}
</script>

<style scoped>
/* 全局样式重置 */
.rank-page {
    min-height: 100vh;
    background-color: #f5f5f5;
    padding-bottom: 40rpx;
    /* 为个人排名卡片留出底部空间 */
}

/* 顶部导航栏样式 */
.header {
    height: 100rpx;
    display: flex;
    align-items: center;
    justify-content: space-between;
    background-color: #ffffff;
    padding: 0 30rpx;
    box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
    position: relative;
}

.header-left {
    width: 60rpx;
    height: 60rpx;
    display: flex;
    justify-content: center;
    align-items: center;
}

.page-title {
    font-size: 32rpx;
    font-weight: bold;
    color: #333;
    position: absolute;
    left: 50%;
    transform: translateX(-50%);
}

.header-right {
    width: 60rpx;
}

/* 排行榜内容 */
.rank-content {
    padding: 30rpx;
    overflow: hidden;
}

/* 标签切换 - 滑动门样式 */
.rank-tabs {
    margin-bottom: 30rpx;
}

.tab-wrapper {
    position: relative;
    display: flex;
    background-color: rgba(255, 255, 255, 0.95);
    border-radius: 30rpx;
    padding: 10rpx;
    box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.05);
    backdrop-filter: blur(10px);
}

.tab-item {
    flex: 1;
    text-align: center;
    padding: 20rpx 0;
    font-size: 28rpx;
    color: #666666;
    border-radius: 25rpx;
    transition: all 0.3s ease;
    z-index: 1;
    position: relative;
}

.tab-item.active {
    color: #ffffff;
}

/* 滑动门指示器 */
.slider {
    position: absolute;
    top: 10rpx;
    left: 10rpx;
    width: calc(33.333%);
    height: calc(100% - 20rpx);
    background-color: #007aff;
    border-radius: 25rpx;
    box-shadow: 0 4rpx 15rpx rgba(0, 122, 255, 0.3);
    transition: transform 0.3s ease;
    z-index: 0;
}

/* 排行榜数据容器 */
.rank-data-container {
    display: block;
}

/* 刷新提示样式 */
.refresh-tip {
    text-align: center;
    margin-bottom: 30rpx;
    padding: 15rpx 0;
}

.tip-text {
    font-size: 24rpx;
    color: #666666;
}

/* 前三名 - 现代设计 */
.top-three {
    display: flex;
    justify-content: space-between;
    align-items: flex-end;
    margin-bottom: 50rpx;
    height: 400rpx;
}

.rank-item {
    display: flex;
    flex-direction: column;
    align-items: center;
    position: relative;
    padding: 30rpx;
    border-radius: 20rpx;
    transition: transform 0.3s ease, box-shadow 0.3s ease;
    backdrop-filter: blur(10px);
    width: 220rpx;
}

.rank-item:active {
    transform: scale(0.98);
}

.first-place {
    height: 100%;
    padding-bottom: 40rpx;
    /* 从上到下渐变，从原颜色到透明 */
    background: linear-gradient(to bottom, #fee271, #fee271, rgba(254, 226, 113, 0));
    /* 底部两个角设置为小半圆 */
    border-bottom-left-radius: 30rpx;
    border-bottom-right-radius: 30rpx;

    .name {
        font-size: 40rpx;
    }

    .study-time {
        font-size: 30rpx;
    }
}

.second-place {
    height: 90%;
    padding-bottom: 30rpx;
    /* 从上到下渐变，从原颜色到透明 */
    background: linear-gradient(to bottom, #9cc3f9, #9cc3f9, rgba(156, 195, 249, 0));
    /* 底部两个角设置为小半圆 */
    border-bottom-left-radius: 30rpx;
    border-bottom-right-radius: 30rpx;
}

.third-place {
    height: 80%;
    padding-bottom: 20rpx;
    /* 从上到下渐变，从原颜色到透明 */
    background: linear-gradient(to bottom, #fec88d, #fec88d, rgba(254, 200, 141, 0));
    /* 底部两个角设置为小半圆 */
    border-bottom-left-radius: 30rpx;
    border-bottom-right-radius: 30rpx;
}

/* 皇冠样式 */
.crown {
    width: 60rpx;
    height: 60rpx;
    position: absolute;
    top: -10rpx;
    z-index: 10;
}

.avatar {
    width: 140rpx;
    height: 140rpx;
    border-radius: 50%;
    margin-bottom: 20rpx;
    border: 6rpx solid #ffffff;
    box-shadow: 0 4rpx 15rpx rgba(0, 0, 0, 0.15);
}

.name {
    font-size: 24rpx;
    font-weight: 600;
    color: #333333;
    margin-bottom: 10rpx;
    max-width: 200rpx;
    text-align: center;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}

.study-time {
    font-size: 26rpx;
    color: #007aff;
    font-weight: 500;
}

.medal {
    position: absolute;
    z-index: 999;
    top: -20rpx;
    width: 80rpx;
    height: 80rpx;
    background-size: contain;
    background-repeat: no-repeat;
    background-position: center;
}

/* 排行榜列表 - 现代设计 */
.rank-list {
    background: rgba(255, 255, 255, 0.95);
    border-radius: 20rpx;
    overflow: hidden;
    box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.05);
    margin-bottom: 30rpx;
    backdrop-filter: blur(10px);
}

.normal-item {
    flex-direction: row;
    justify-content: space-between;
    align-items: center;
    padding: 30rpx;
    border-bottom: 2rpx solid rgba(0, 122, 255, 0.1);
    height: auto;
    transition: background-color 0.3s ease;
    width: 100%;
}

.normal-item:last-child {
    border-bottom: none;
}

.normal-item:active {
    background-color: rgba(0, 122, 255, 0.05);
}

.rank-num {
    width: 60rpx;
    text-align: center;
    font-size: 28rpx;
    font-weight: 700;
    color: #999999;
}

.user-avatar {
    width: 80rpx;
    height: 80rpx;
    border-radius: 50%;
    margin: 0 20rpx;
    border: 3rpx solid #f0f0f0;
}

.user-name {
    flex: 1;
    font-size: 28rpx;
    color: #333333;
    font-weight: 500;
}

.user-study-time {
    font-size: 28rpx;
    font-weight: 600;
    color: #007aff;
    margin-left: 20rpx;
}

/* 加载状态 */
.loading {
    text-align: center;
    padding: 40rpx;
    color: #999999;
    font-size: 28rpx;
}

/* 个人排名卡片 - 新增样式 */
.personal-rank-card {
    background: rgba(255, 255, 255, 0.95);
    border-radius: 20rpx;
    padding: 30rpx;
    box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.05);
    margin-top: 30rpx;
    backdrop-filter: blur(10px);
}

.card-title {
    font-size: 32rpx;
    font-weight: bold;
    color: #333;
    margin-bottom: 20rpx;
    text-align: center;
}

.personal-item {
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    align-items: center;
    padding: 20rpx;
    border-radius: 15rpx;
    background-color: rgba(0, 122, 255, 0.1);
    border: 2rpx solid rgba(0, 122, 255, 0.2);
}

.personal-item .rank-num {
    color: #007aff;
    font-weight: bold;
}

.rank-tip {
    text-align: center;
    margin-top: 20rpx;
    font-size: 24rpx;
    color: #666;
    padding: 15rpx;
    background-color: rgba(0, 122, 255, 0.05);
    border-radius: 10rpx;
}

/* 适配不同设备的响应式设计 */
@media screen and (min-width: 768px) {
    .rank-content {
        max-width: 600rpx;
        margin: 0 auto;
    }
}
</style>